
/*
 * @Author: 于建霞
 * @Date: 2020-11-23 15:36:39
 * @Last Modified by: 于建霞
 * @Last Modified time: 2020-11-Mo 03:41:50
 * 
 * * @description:  添加随行人员弹框
 */

import React, { useState, useCallback, useRef, useEffect, memo} from 'react';
import { Modal, Button, DatePicker, Checkbox, Input, Select, message } from 'antd';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { formatFlightNo } from '@/utils/pagesGeneralMethods'; // 页面通用方法
import { getChioceVipAcmp, saveAcmps, getVipEntry } from '../../service';
import { getScanResults } from '../../scanParsing.js';
import styles from '../../index.less'
import moment from 'moment';

/**
* @param {addOrGreet, //添加/迎接类型（add/greet）
* addEntourageVisible, //显隐
* setFarewellVisible //控制显示函数
* } props 
*/

let saveArr = [];
const AddEntourage = (props) => {
    const { addOrGreet, 
        addEntourageVisible, 
        setAddEntourageVisible,
        selectData, 
        addEntourageSelectRow, 
        reloadTable,
        checkedAlongs,
        setCheckedAlongs,
        scanCodeToEntourage,
        handleGreetAddFlag
        // dataSourceFlag //区别数据来源是点击还是扫描
    } = props;

    const ref = useRef();
    // 第一次加载
    const [firstLoadFlag, setFirstLoadFlag] = useState(true);
    const [hasData, setHasData] = useState(true); //是否查询出数据
    const [selectRow, setSelectRow] = useState(props.passengers || []);// 选中的项
    const [selectedRowKeys, setSelectedRowKeys] = useState(props.passengersIds);// 选中项的id
    const [addSelectRow, setAddSelectRow] = useState([]);// 要添加选中的项
    const [scanPassengerData, setScanPassengerData] = useState([]);// 查询接口获取的数据
    // const [sourceSymbol, setSourceSymbol] = useState('click');// 要添加选中的项
    const [initValue, setInitValue] = useState({});// 父组件的传值
        
    const { run:saveAcmpsFun, loading:saveAcmpsLoading } = useRequest((params)=> saveAcmps(params),{
        manual: true,
        onSuccess: (data) => {
            setAddEntourageVisible(false);
            message.success('操作成功');
            setFirstLoadFlag(true);
            setAddSelectRow([]);
            reloadTable();
        }
    })
    useEffect(() => {
        if (addEntourageSelectRow?.length > 0) {
            setInitValue(addEntourageSelectRow[0])
            ref.current && ref.current.setFieldsValue({
                flightNo: addEntourageSelectRow[0].flightNo,
                orgCityAirp: addEntourageSelectRow[0].org,
            })
        }
    }, [addEntourageSelectRow])

    // 根据扫描或输入提取旅客信息
    const { run:getVipInfoFun, loading:getVipInfoLoading } = useRequest((flightInfo)=> getVipEntry(flightInfo),{
        manual: true,
        onSuccess: (data) => {
            if(!data || JSON.stringify(data) == '{}') return message.error('未查询到旅客信息');
            setScanPassengerData([data]);
            if (addSelectRow.length > 10)  {
                return message.error('最多添加10个随行人员');
            }
            // console.log('saveArr', saveArr)
            
            let noRepeatArr = [...saveArr,...[data]]
            let newArr = [];
            let obj = {};
            for (var i = 0; i < noRepeatArr.length; i++) {
                if (!obj[noRepeatArr[i].paxId]) {
                    newArr.push(noRepeatArr[i]);
                    obj[noRepeatArr[i].paxId] = true;
                }
            }
            if (newArr?.length > 10)  {
                return message.error('最多添加10个随行人员');
            }
            setAddSelectRow(newArr);
        }
    })
    // 要添加随行人员的旅客信息
    useEffect(() => {
     setAddSelectRow(checkedAlongs);
    }, [checkedAlongs,addEntourageVisible])

    useEffect(() => {
        if (scanCodeToEntourage) {
            // 扫码结果有值-提取旅客-添加到列表数据中
            let scanResultsObj = getScanResults(scanCodeToEntourage);
            if (scanResultsObj) {
                let flightInfo = {
                    lclDptDate:moment(scanResultsObj.filghtDate).format('YYYY-MM-DD'),
                    tktNo:scanResultsObj.ticketNo,
                    flightNo:scanResultsObj.flightNo,
                    paxName:scanResultsObj.paxName,
                    orgCityAirp:scanResultsObj.orgCityAirp,
                    bordNo:Number(scanResultsObj.serialNo)+'',  //消除多余的0占位符
                }
                // console.log('000SelectRowaddSelectRow', addSelectRow)
                saveArr = JSON.parse(JSON.stringify(addSelectRow))
                // console.log('saveArrsaveArr', saveArr)
                getVipInfoFun(flightInfo);
             }else{
                message.error('非法条码');
             }
        }
    }, [scanCodeToEntourage])

    // useEffect(() => {
    //     setSourceSymbol(dataSourceFlag);
    // }, [dataSourceFlag])
    

    // 提交选中项
    const handleOk = () => {
        if (addSelectRow.length === 0) {
            return message.error(`请选择要${addOrGreet === "add" ? "添加" : "迎接"}的随行人员`) 
        }
        if (addSelectRow.length > 10)  {
            return message.error('最多添加10个随行人员');
        }
        // 迎接
        if(addOrGreet === "greet") {
            setFirstLoadFlag(true);
            setCheckedAlongs(addSelectRow);
            handleGreetAddFlag&&handleGreetAddFlag(false);
            return setAddEntourageVisible(false);
        }
        // let idsArr = [];
        // for (const item of addSelectRow) {
        //     idsArr.push(item.paxId);
        // }
        let saveparams =  {
            // acmpIds:idsArr.join(','),
            acmpList:JSON.stringify(addSelectRow),
            id:addEntourageSelectRow[0].id,
        };
        saveAcmpsFun(saveparams);
    }
    // 关闭弹框
    const handleCancel = () => {
        setAddEntourageVisible(false);
        setFirstLoadFlag(true);
        setAddSelectRow([]);
        handleGreetAddFlag&&handleGreetAddFlag(false);
    }
    // 选中项
    const changeRows = (selectedRowKeys, selectedRows) => {
        setSelectRow([...selectedRows]);
        setSelectedRowKeys([...selectedRowKeys]);
    }
    
    // 搜索前的回调
    const beforeSearchSubmit = useCallback(params => {
        // setSourceSymbol('click')
        params['lclDptDate'] = params.lclDptDate ? params.lclDptDate.format('YYYY-MM-DD') : '';
        if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
            ref.current && ref.current.setFieldsValue({
                lclDptDate: initValue.lclDptDate ? moment(initValue.lclDptDate).format('YYYY-MM-DD') : '',
                flightNo: initValue.flightNo,
                orgCityAirp: initValue.org,
            });
            params.flightNo = initValue.flightNo;
            params.orgCityAirp = initValue.org;
        }
        return params;
    }, []);
    // 删除添加随行人员列表项
    const delAddItemFun = (row) => {
        let temparr = [...addSelectRow].filter(item => item.paxId !== row.paxId);
        saveArr = JSON.parse(JSON.stringify(temparr));
        setAddSelectRow(saveArr);
    }

    let columns = [
        // {
        //     title: (_, type) => (type === 'table' ? '姓名' : '旅客姓名'),
        //     width: 120,
        //     dataIndex: 'paxName',
        //     renderFormItem: (_, { defaultRender, ...rest }) => {
        //         return <Input {...rest} placeholder="请输入旅客姓名" />;
        //     },
        // },
        {
            title: 'PNR',
            dataIndex: 'pnrRef',
            hideInSearch: true,
            width: 130
        },
        {
            title: '旅客姓名',
            order: 2,
            filters: false,
            dataIndex: 'paxName',
            width: 120,
        },
        {
            title: '航班状态',
            hideInSearch: true,
            dataIndex: 'flightStatus',
            width: 130,
            filters: false,
            valueEnum: {
                null: {
                  text: '正常',
                },
                'D': {
                  text: '延误',
                },
                'C': {
                  text: '取消',
                },
                'N': {
                  text: '正常',
                },
              },
        },
        {
            title: '航班日期',
            dataIndex: 'lclDptDate',
            order: 4,
            hideInTable: true,
            width: 150,
            renderFormItem: (_, { ...rest }) => {
                return (
                    <DatePicker
                        showTime={{ format: 'YYYY-MM-DD' }}
                        style={{ width: '100%' }}
                        allowClear={false}
                        format='YYYY-MM-DD'
                        {...rest}
                    />
                );
            },
        },
        {
            title: '航班号',
            dataIndex: 'flightNo',
            key: 'flightNo',
            width: 130,
            order: 5,
            renderFormItem: (_, { defaultRender, ...rest }) => {
                return <Input
                {...rest}
                onChange={e => {
                  e.target.value = formatFlightNo(e.target.value);
                  rest.onChange(e.target.value)
                }}
                 maxLength={6} placeholder="3U" />;
            },
        },
        {
            title: '起飞时间',
            hideInSearch: true,
            dataIndex: 'std',
            width: 180
        },
        {
            title: '登机口',
            hideInSearch: true,
            dataIndex: 'gate',
            width: 130
        },
        {
            title: '始发站',
            order: 3,
            dataIndex: 'org',
            key:"orgCityAirp",
            width: 200,
            renderFormItem: (_, { ...rest }, form) => {
                return (
                  <Select
                    allowClear={false}
                    showSearch
                    placeholder='请选择'
                    defaultActiveFirstOption={false}
                    showArrow={false}
                    filterOption={true}
                    optionFilterProp="children"
                    notFoundContent={null}
                    {...rest}
                  >
                    {
                      selectData && selectData.map((v, i) => {
                        return (
                          <Option key={v.CITY3CODE} value={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                        )
                      })
                    }
                  </Select>
                );
              }
        },
        {
            title: '目的地',
            hideInSearch: true,
            dataIndex: 'dst',
            width: 130
        },
        {
            title: '航线',
            hideInSearch: true,
            dataIndex: 'fltRoute',
            width: 130
        },
        // {
        //     title: '登机牌条码',
        //     dataIndex: 'bordCardCode2',
        //     order: 1,
        //     width: 130
        // },
    ];
    let columns1 = [...columns, {
        title: '操作',
        valueType: 'option',
        width: 80,
        fixed: 'left',
        align: "center",
        render: (text, row, _, action) => [
            <Button type="link" onClick={() => delAddItemFun(row)}>
                删除
          </Button>
        ],
    }];
    return (
        <Modal
            title="添加随行人员"
            visible={addEntourageVisible}
            maskClosable={false}
            destroyOnClose={true}
            className={styles.addEntourage}
            width="84%"
            getContainer={()=>document.getElementById('parentBox')}
            zIndex="1001"
            onCancel={handleCancel}
            footer={
                <>
                    <Button onClick={handleCancel}>取消</Button>
                    {/* <Button loading={saveAcmpsLoading} onClick={handleOk}>{addOrGreet === "add" ? "添加" : "迎接"}</Button> */}
                    <Button loading={saveAcmpsLoading} onClick={handleOk}>添加</Button>
                </>
            }
        >
            {/* 随行人员信息 */}
            <ProTable
                options={false}
                size="small" 
                formRef={ref}
                scroll={{ x: 1000, y: 300 }}
                search={{
                    collapsed: false, //默认展开
                    collapseRender: () => false, //不要折叠按钮
                    span: { //设置排列方式
                        xs: 24,
                        sm: 24,
                        md: 8,
                        lg: 8,
                        xl: 8,
                        xxl: 8,
                    }
                }}
                loading={false}
                pagination={{
                    showSizeChanger: true,
                    showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`,
                    pageSize:10
                  }}
                rowKey="paxId"
                headerTitle={false}
                request={params => {
                    let searchObj ={...params};
                    if (!params['lclDptDate']) {
                        if (initValue.lclDptDate) {
                            params['lclDptDate'] = moment(initValue.lclDptDate).format('YYYY-MM-DD');
                            ref.current && ref.current.setFieldsValue({
                                lclDptDate: moment(initValue.lclDptDate),
                            })
                        }else{
                            params['lclDptDate'] = moment().format('YYYY-MM-DD');
                            ref.current && ref.current.setFieldsValue({
                                lclDptDate: moment(),
                            })
                        }
                    }else{
                        ref.current && ref.current.setFieldsValue({
                            lclDptDate: moment(params.lclDptDate),
                        })
                    }
                    ref.current && ref.current.setFieldsValue({
                        flightNo: params.flightNo ? params.flightNo : initValue.flightNo,
                        orgCityAirp: params.orgCityAirp ? params.orgCityAirp : initValue.org,
                        // lclDptDate: initValue.lclDptDate ? moment(initValue.lclDptDate) : (params.lclDptDate ? moment(initValue.lclDptDate) : moment()),
                    })
                    searchObj = {...params,...{
                        flightNo: params.flightNo ? params.flightNo : initValue.flightNo,
                        orgCityAirp: params.orgCityAirp ? params.orgCityAirp : initValue.org,
                        // lclDptDate: initValue.lclDptDate ? moment(initValue.lclDptDate).format('YYYY-MM-DD') : (params.lclDptDate ? moment(initValue.lclDptDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')),
                    }}
                    // 查询就走接口， 扫描就直接展示扫描结果
                    // if (sourceSymbol === 'click') {
                        return getChioceVipAcmp({ ...searchObj,lclDptDate:moment(searchObj?.lclDptDate).format('YYYY-MM-DD'),paxId:initValue.paxId});
                    // }else{
                    //     return Promise.resolve({
                    //         data: [],
                    //         success: true,
                    //     }); 
                    // }
                }}
                postData={data => {
                    setHasData(data ? false : true);
                    return data;
                }}
                beforeSearchSubmit={beforeSearchSubmit}
                columns={columns}
                rowSelection={{ selectedRowKeys, onChange: changeRows }}
                tableAlertRender={false}
                toolBarRender={false}
            />
            {/* 选择人员 */}
            <div style={{ textAlign: "right", margin: "10px 0" }}>
                <Button type="primary" disabled={hasData} onClick={() => { 
                    let noRepeatArr = [...selectRow,...addSelectRow];
                    let newArr = [];
                    let obj = {};
                    for (var i = 0; i < noRepeatArr.length; i++) {
                        if (!obj[noRepeatArr[i].paxId]) {
                            newArr.push(noRepeatArr[i]);
                            obj[noRepeatArr[i].paxId] = true;
                        }
                    }
                    if (newArr?.length > 10)  {
                        return message.error('最多添加10个随行人员');
                    }
                    saveArr = JSON.parse(JSON.stringify(newArr))
                    setAddSelectRow([...newArr]);
                    }}>选择</Button>
            </div>
            {/* 添加-随行人员列表 */}
            <ProTable
                options={false}
                size="small"
                dataSource={addSelectRow}
                scroll={{ x: 1000, y: 300 }}
                headerTitle="添加随行人员列表"
                search={false}
                loading={false}
                pagination={false}
                rowKey="paxId"
                loading={getVipInfoLoading}
                columns={columns1}
                rowSelection={false}
                tableAlertRender={false}
            />
        </Modal>
    )
}

/**
 * 优化渲染
 */
function carefulRender(prevProps, nextProps) {
    if (JSON.stringify(prevProps) != JSON.stringify(nextProps)) {
        return false
    } else {
        return true
    }
}

export default memo(AddEntourage, carefulRender);